/*
 * Activiti Modeler component part of the Activiti project
 * Copyright 2005-2014 Alfresco Software, Ltd. All rights reserved.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

/*
 * Assignment
 */
var KisBpmAssignmentCtrl = [ '$scope', '$modal', '$http', function($scope, $modal, $http) {

	//$scope.range = {};
	var token = eval('(' +  window.sessionStorage.getItem('cloud-access_token')+ ')');

	$http({
		method: 'GET',
		url: '/admin/role/list',
		headers: {
			'Authorization': "Bearer " + token.content
		}
	}).then(function successCallback(response) {
		// 请求成功执行代码
		$scope.range = response.data.data;

		// Config for the modal window
		var opts = {
			template:  'editor-app/configuration/properties/assignment-popup.html?version=' + Date.now(),
			scope: $scope
		};

		// Open the dialog
		$modal(opts);

	}, function errorCallback(response) {
		// 请求失败执行代码
	});
}];

var KisBpmAssignmentPopupCtrl = [ '$scope', function($scope) {
    	
    // Put json representing assignment on scope
    if ($scope.property.value !== undefined && $scope.property.value !== null
        && $scope.property.value.assignment !== undefined
        && $scope.property.value.assignment !== null) 
    {
        $scope.assignment = $scope.property.value.assignment;
    } else {
        $scope.assignment = {};
    }

    if ($scope.assignment.candidateUsers == undefined || $scope.assignment.candidateUsers.length == 0)
    {
    	$scope.assignment.candidateUsers = [{value: ''}];
    }
    
    // Click handler for + button after enum value
    var userValueIndex = 1;
    $scope.addCandidateUserValue = function(index) {
        $scope.assignment.candidateUsers.splice(index + 1, 0, {value: 'value ' + userValueIndex++});
    };

    // Click handler for - button after enum value
    $scope.removeCandidateUserValue = function(index) {
        $scope.assignment.candidateUsers.splice(index, 1);
    };
    
    if ($scope.assignment.candidateGroups == undefined || $scope.assignment.candidateGroups.length == 0)
    {
    	$scope.assignment.candidateGroups = [{value: ''}];
    }
    
    var groupValueIndex = 1;
    $scope.addCandidateGroupValue = function(index) {
        $scope.assignment.candidateGroups.splice(index + 1, 0, {value: 'value ' + groupValueIndex++});
    };

    // Click handler for - button after enum value
    $scope.removeCandidateGroupValue = function(index) {
        $scope.assignment.candidateGroups.splice(index, 1);
    };

    $scope.save = function() {

        $scope.property.value = {};
        handleAssignmentInput($scope);

        //edit by liun 因为这里采用了select2插件进行数据批量选择，所以重新对$scope.property进行赋值
		var assignmentArr = $scope.select2.map(function(item){
			if(item.indexOf('roleSelf') > 0){
				return item;
			} else {
				return ('ROLE-' + item);
			}
		});

		var assignmentStr = assignmentArr.join(',');

		$scope.assignment.assignee = assignmentStr;

		$scope.property.value.assignment = $scope.assignment;
        
        $scope.updatePropertyInModel($scope.property);
        $scope.close();
    };

    // Close button handler
    $scope.close = function() {
    	handleAssignmentInput($scope);
    	$scope.property.mode = 'read';
    	$scope.$hide();
    };
    
    var handleAssignmentInput = function($scope) {
    	if ($scope.assignment.candidateUsers)
    	{
	    	var emptyUsers = true;
	    	var toRemoveIndexes = [];
	        for (var i = 0; i < $scope.assignment.candidateUsers.length; i++)
	        {
	        	if ($scope.assignment.candidateUsers[i].value != '')
	        	{
	        		emptyUsers = false;
	        	}
	        	else
	        	{
	        		toRemoveIndexes[toRemoveIndexes.length] = i;
	        	}
	        }
	        
	        for (var i = 0; i < toRemoveIndexes.length; i++)
	        {
	        	$scope.assignment.candidateUsers.splice(toRemoveIndexes[i], 1);
	        }
	        
	        if (emptyUsers)
	        {
	        	$scope.assignment.candidateUsers = undefined;
	        }
    	}
        
    	if ($scope.assignment.candidateGroups)
    	{
	        var emptyGroups = true;
	        var toRemoveIndexes = [];
	        for (var i = 0; i < $scope.assignment.candidateGroups.length; i++)
	        {
	        	if ($scope.assignment.candidateGroups[i].value != '')
	        	{
	        		emptyGroups = false;
	        	}
	        	else
	        	{
	        		toRemoveIndexes[toRemoveIndexes.length] = i;
	        	}
	        }
	        
	        for (var i = 0; i < toRemoveIndexes.length; i++)
	        {
	        	$scope.assignment.candidateGroups.splice(toRemoveIndexes[i], 1);
	        }
	        
	        if (emptyGroups)
	        {
	        	$scope.assignment.candidateGroups = undefined;
	        }
    	}
    };
}];

/*
 * Assignment Display
 */
var KisBpmAssignmentShowCtrl = [ '$scope', '$http', '$q', function($scope, $http, $q) {

	//对存储的assignee值进行指定转换成对应的中文assigneeShow，展示在页面之上
	var assignee = $scope.property.value.assignment.assignee;
	var assigneeArr;
	$scope.property.value.assignment.assigneeShow = '';


	if('' != assignee) {
		//按照逗号拆分字符，判断当前字符类型，并获取所有的对应角色名称
		assigneeArr = assignee.split(',');

		assigneeArr = assigneeArr.forEach(function(item){
			if(item.indexOf('roleSelf') >= 0) {
				//如果当前assignee为发起人
				$scope.property.value.assignment.assigneeShow += '发起人,';
			} else if(item.indexOf('ROLE') >= 0) {
				//如果当前assignee为角色id
				var roleId = item.split('-')[1];

				asyncReq(roleId).then(
					function(greeting) {
						//alert('Success: ' + greeting);
						//assigneeShow.push(greeting);
						$scope.property.value.assignment.assigneeShow = $scope.property.value.assignment.assigneeShow + greeting + ',';
					},
					function(reason) {
						//alert('Failed: ' + reason);
						assigneeShow.push(item);
					},
					function(update) {
						//alert('Got notification: ' + update);
						assigneeShow.push(item);
					});
			} else {
				$scope.property.value.assignment.assigneeShow = $scope.property.value.assignment.assigneeShow + item + ',';
			}
		});

		//$scope.property.value.assignment.assigneeShow = assigneeShow.join();
	}

	function asyncReq(roleId) {
		var deferred = $q.defer();

		//根据当前角色id查询对应角色信息
		var token = eval('(' +  window.sessionStorage.getItem('cloud-access_token')+ ')');

		$http({
			method: 'GET',
			url: '/admin/role/' + roleId,
			headers: {
				'Authorization': "Bearer " + token.content
			}
		}).then(function successCallback(response) {
			// 请求成功执行代码
			//return response.data.data.roleName;
			deferred.resolve(response.data.data.roleName);
			//assigneeShow.push(response.data.data.roleName);
		}, function errorCallback(response) {
			// 请求失败执行代码
			//assigneeShow.push(item);
			deferred.reject(roleId);
		});

		return deferred.promise;
	}


}];